# encoding: utf-8
import smtplib
from email.header import make_header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import argparse

mail_host = 'mail.iflytek.com'
mail_user = 'dcservice@iflytek.com'
mail_pass = 'Yxd7KxaQYbH5AcB5'
mail_postfix = 'iflytek.com'


def common_sendmail(mail_to, subject, content):
    mail_host = 'mail.iflytek.com'
    mail_user = 'dcservice@iflytek.com'
    mail_pass = 'Yxd7KxaQYbH5AcB5'
    mail_postfix = 'iflytek.com'
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    # msg = MIMEText(content, 'plain', 'utf-8')
    msg = MIMEMultipart()
    msg["Accept-Language"] = "zh-CN"
    msg["Accept-Charset"] = "ISO-8859-1,utf-8"
    # msg['Subject'] = Header(subject, 'utf-8')
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = mail_to
    txt = MIMEText(content, 'html', 'utf-8')
    msg.attach(txt)

    global sendstatus
    global senderr

    try:
        # mail_pass = base64.b64decode(mail_pass).decode("utf-8")
        smtp = smtplib.SMTP_SSL(mail_host, 465)
        smtp.login(mail_user,mail_pass)
        if ';' in mail_to:
            smtp.sendmail(me,mail_to.split(';'),msg.as_string())
        elif ',' in mail_to:
            smtp.sendmail(me,mail_to.split(','),msg.as_string())
        else:
            smtp.sendmail(me,mail_to,msg.as_string())
        smtp.close()
        sendstatus = True
        return 'success'
    except Exception as e:
        senderr=str(e)
        sendstatus = False

        return senderr


def send_mail(mail_to: list, subject, content, ccs: list = None, attachments: list = None):
    """
    发送邮件
    :param mail_to: 邮件接收人列表
    :param subject: 邮件主题
    :param content: 邮件内容
    :param ccs: 抄送人列表
    :param attachments: 附件列表，[{"content": 包含文件内容的类文件对象，有.read()方法返回文件字节, "filename": 文件名称}]
    """
    if isinstance(mail_to, str):
        mail_to = [mail_to]

    if isinstance(ccs, str):
        ccs = [ccs]
    elif ccs is None:
        ccs = []

    # 最终mail_to和ccs必须是数组

    me = mail_user
    msg = MIMEMultipart()
    msg["Accept-Language"] = "zh-CN"
    msg["Accept-Charset"] = "ISO-8859-1,utf-8"
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = ';'.join(mail_to)
    txt = MIMEText(content, 'html', 'utf-8')
    msg.attach(txt)

    if ccs:
        msg['Cc'] = ';'.join(ccs)  # 抄送人

    if attachments:
        # 添加附件
        for attachment in attachments:
            file_content = attachment['content']
            filename = attachment['filename']

            file_msg = MIMEText(file_content.read(), 'base64', 'UTF-8')
            file_msg["Content-Type"] = 'application/octet-stream;name="%s"' % make_header([(filename, 'UTF-8')]).encode(
                'UTF-8')
            file_msg["Content-Disposition"] = 'attachment;filename= "%s"' % make_header([(filename, 'UTF-8')]).encode(
                'UTF-8')
            msg.attach(file_msg)

    email_list = []
    for email in mail_to + ccs:
        if '@' not in email:
            email = email + "@iflytek.com"

        if email not in email_list:
            email_list.append(email)

    mail_to = email_list

    try:
        smtp = smtplib.SMTP_SSL(mail_host, 465)
        smtp.connect(mail_host)
        smtp.login(mail_user, mail_pass)
        smtp.sendmail(me, mail_to, msg.as_string())
        smtp.close()
    except Exception as e:
        return False, str(e)
    return True, 'success'


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Send mail to user for zabbix alerting')
    parser.add_argument('mail_to', action="store", help='The address of the E-mail that send to user ')
    parser.add_argument('subject', action="store", help='The subject of the E-mail')
    parser.add_argument('content', action="store", help='The content of the E-mail')
    args = parser.parse_args()

    res, msg = send_mail(args.mail_to, args.subject, args.content)
    print(res, msg)
